package l.l.w.leetcode.AddTwoNumbers;

/**
 * Created by llw on 2017/8/22.
 */
public class AddTwoNumbers {

    /**
     * 循环链表 进行增加
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
        int sum=l1.val+l2.val;
        ListNode result = new ListNode(sum % 10);
        int jinwei=sum/10;
        ListNode head = result;
        while(l1.next != null && l2.next!=null){
            l1=l1.next;
            l2=l2.next;
            sum=l1.val+l2.val+jinwei;
            result.next=new ListNode(sum % 10);
            result = result.next;

            jinwei = sum/10;
        }
        ListNode l3 = null;
        if(l1.next!=null){
            l3=l1.next;
        }else if(l2.next!=null){
            l3=l2.next;
        }
        while(jinwei != 0 && l3!=null){
            sum = l3.val+jinwei;
            result.next = new ListNode(sum%10);
            result = result.next;
            jinwei = sum/10;
            l3=l3.next;
        }
        if(jinwei ==0)
            result.next = l3;
        if(l3==null && jinwei !=0){
            result.next=new ListNode(jinwei);
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(5);
//        l1.next = new ListNode(9);
//        l1.next.next = new ListNode(9);
//        l1.next.next.next = new ListNode(9);
//        l1.next.next.next.next = new ListNode(9);
        ListNode l2 = new ListNode(5);
//        l2.next = new ListNode(6);
//        l2.next.next = new ListNode(4);

        ListNode listNode = new AddTwoNumbers().addTwoNumbers1(l1, l2);
        while(listNode != null){
            System.out.print(listNode.val);
            listNode = listNode.next;
        }
    }
}
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}
